package logic

import (
	"context"
	"errors"
	"gorm.io/gorm"
	"shunovel/models/mysql"

	"shunovel/shunovelrpc/internal/svc"
	"shunovel/shunovelrpc/shunovelrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type BookUpdateLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewBookUpdateLogic(ctx context.Context, svcCtx *svc.ServiceContext) *BookUpdateLogic {
	return &BookUpdateLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *BookUpdateLogic) BookUpdate(in *shunovelrpc.BookUpdateRequest) (*shunovelrpc.BookUpdateResponse, error) {
	// todo: add your logic here and delete this line
	var findBook mysql.Book
	mysql.DB.Debug().Where("id=?", in.BookId).Find(&findBook)
	if in.BookId == 0 {
		return nil, errors.New("图书不存在,不允许修改")
	}
	book := mysql.Book{
		Model:  gorm.Model{ID: uint(in.BookId)},
		Title:  in.Title,
		Image:  in.Image,
		Text:   in.Text,
		UserId: int(in.UserId),
	}
	mysql.DB.Debug().Updates(&book)

	return &shunovelrpc.BookUpdateResponse{
		BookId: int64(book.ID),
	}, nil
}
